import Vue from 'vue'
import { AxiosRequestConfig } from 'axios'
import { isObject } from 'assets/utils'
import symbolManager from 'assets/symbolManager'

// module的axios配置
const configSub: AxiosRequestConfig = {
    timeout: 600000
}
// 合并config
function setConfig (config) {
    config = Object.assign({}, configSub, config)
    if (process.env.COMPILE_MODE === 'lib') {
        config.scopeName = process.env.APP_SCOPE_NAME
    }
    return config
}

function createProxy (func: Function) {
    return new Proxy(func, {
        apply (target, ctx, args) {
            const key = symbolManager.get('httpConfig')
            if (isObject(Vue.prototype[key])) {
                if (
                    isObject(args[args.length - 1])
                ) {
                    args[args.length - 1] = {
                        ...Vue.prototype[key],
                        ...args[args.length - 1]
                    }
                } else {
                    args.push(Vue.prototype[key])
                }
            }
            return Reflect.apply(target, ctx, args)
        }
    })
}

export const _get = createProxy(function (url, succ?, fail?, config: Object = {}) {
    const $get: any = Vue.prototype.$mg_get
    config = setConfig(config)
    $get(url, succ, fail, config)
})

export const _delete = createProxy(function (url, succ?, fail?, config: Object = {}) {
    const $delete: any = Vue.prototype.$mg_delete
    config = setConfig(config)
    $delete(url, succ, fail, config)
}) 

export const _post = createProxy(function (url: string, param: any, succ?, fail?, config: Object = {}) {
    const $post: any = Vue.prototype.$mg_post
    config = setConfig(config)
    $post(url, param, succ, fail, config)
}) 

export const _put = createProxy(function (url, param, succ?, fail?, config: Object = {}) {
    const $put: any = Vue.prototype.$mg_put
    config = setConfig(config)
    $put(url, param, succ, fail, config)
}) 
